/**
 * Created by Administrator on 2017/9/11.
 */

import '../common/utils/lib'
import 'react-quill/dist/quill.snow.css';
import {Route, HashRouter, NavLink, Redirect, Switch} from 'react-router-dom';
import {Menu, Icon, Layout} from 'antd';
const SubMenu = Menu.SubMenu;
const {Header, Content, Sider} = Layout;
import '../css/common.less'

import AppService from '../common/utils/app.service'
import _Header from '../component/header.component'
import ScrollToTop from '../component/scrollToTop.component'
// import BannerComponent from '../component/Banner/index.component'
import AdminComponent from '../component/Admin/index.component'
import PlayRecordComponent from '../component/PlayRecord/index.component'
import BaseSettingComponent from '../component/BaseSetting/index.component'
import QuestionComponent from '../component/Question/index.component'
import ArticleComponent from '../component/Article/index.component'
import MusicComponent from '../component/Music/index.component'




const navs = [
  {
    key: 'playRecord_manager',
        name: '对战记录管理',
    children: [ ],
    icon: 'team',
    path: '/playRecord/manager',
    component: (props) => {
    return <PlayRecordComponent {...props}/>
    }
  },
//   {
//     key: 'baseSetting_manager',
//         name: '基础内容管理',
//     children: [ ],
   
//     path: '/baseSetting/manager',
//     component: (props) => {
//     return <BaseSettingComponent {...props}/>
//     }
// },
  {
    key: 'question_manager',
        name: '题库管理',
    children: [ ],
    icon: 'file',
    path: '/playRecord/manager',
    component: (props) => {
    return <QuestionComponent {...props}/>
    }
},
  // {
  //   key: 'article_manager',
  //       name: '文章管理',
  //   children: [ ],
   
  //   path: '/article/manager',
  //   component: (props) => {
  //   return <ArticleComponent {...props}/>
  //   }
  // },
  
  // {
  //   key: 'music',
  //       name: '音乐管理',
  //   children: [ ],
   
  //   path: '/music/manager',
  //   component: (props) => {
  //   return <MusicComponent {...props}/>
  //   }
  // },

  {
      key: 'user',
      name: '用户管理',
      icon: 'user',
      path: '/admin/userlist',
      children: [],
      component: (props) => {
          return <AdminComponent {...props}/>
      }
  },
  {
    key: 'admin',
    name: '系统设置',
    icon: 'setting',
    children: [
      {
        key: 'admin_user',
        name: '管理员',
        path: '/admin/user',
        component: (props) => {
          return <AdminComponent {...props}/>
        }
      },
        {
            key: 'admin_role',
            name: '角色管理',
            path: '/admin/role',
            component: (props) => {
                return <AdminComponent {...props}/>
            }
        }
    ]
  },

  ];

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: false,
      defaultSelectedKeys: 'information_manager',
      defaultOpenKeys: 'information_manager',
      loginName: '',
      permission: [],
        superAdmin:false
    }
  }

  componentWillMount() {
    let _this = this;
    AppService.getRequest('admin/mycenter/getLoginUser').then(response => {
      if (response.body) {
          //测试用数据
          // let res = response.body.permissionCodes;
          // res = res.concat(['article_student']);
         
        _this.setState({
          loginName: response.body.userName,
          permission: response.body.permissionCodes,
          superAdmin:response.body.superAdmin
        })
          sessionStorage.setItem('superAdmin',response.body.superAdmin);
        //if(!response.body.superAdmin){
        //    _this.setState({
        //        channelId:response.body.channelId
        //    });
        //    sessionStorage.setItem('channelId',response.body.channelId);
        //}
      }
    })
    if (window.location.hash == '#/' || window.location.hash == '') {
      return
    }
    let path = window.location.hash.substring(1).split('/');
    this.setState({
      defaultSelectedKeys: path[1] + '_' + path[2],
      defaultOpenKeys: path[1],
    })
  }
    getMenuItem = () => {
        let _this = this
        return navs.map(record => {
         
         
       //
            if (record.children.length == 0 && this.state.permission.indexOf(record.key) > -1) {
       
                return ( <Menu.Item key={record.key}>
                  <NavLink to={record.path}> <Icon type={record.icon}/><span
                      className="nav-text">{record.name}</span></NavLink>
                </Menu.Item>)
            } else if (record.children.length != 0) {
                function hasPermission(item) {
                    return _this.state.permission.indexOf(item.key) > -1
                }

                if (record.children.some(hasPermission)) {
                    return (
                        <SubMenu key={record.key} title={<span><Icon type={record.icon}/>{record.name}</span>}>
                            {
                                record.children.map(item => {
                                    if (_this.state.permission.indexOf(item.key) > -1) {
                                        return (
                                            <Menu.Item key={item.key}>
                                              <NavLink to={item.path}> <span className="nav-text">{item.name}</span></NavLink>
                                            </Menu.Item>
                                        )
                                    }
                                })
                            }
                        </SubMenu>
                    )
                }
            }
        })
    }


  getLinkUrl = (data) => {
    return `/${data.split('_').join('/')}`
  };

  authority = (permission, component, props) => {
    if (true) {
      return component(props)
    } else {
      return <NoAuthority/>
    }
  };

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }

  render() {
    let _this = this;
    const superAdmin = _this.state.superAdmin;
    return (
      <HashRouter>
        <Layout>
          <Sider
            trigger={null}
            collapsible
            collapsed={this.state.collapsed}
          >
            <div className="logo">对战hardcoder管理后台</div>
            <Menu theme="dark" mode="inline" defaultSelectedKeys={[this.state.defaultSelectedKeys]}
                  defaultOpenKeys={[this.state.defaultOpenKeys]}>
              {this.getMenuItem()}
            </Menu>
          </Sider>
          <Layout>
            <Header style={{background: '#fff', paddingLeft: 0}}>
              <Icon
                className="trigger"
                type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
                onClick={this.toggle}
              />
              <_Header loginName={this.state.loginName}></_Header>
            </Header>
            <Content style={{margin: '0px 16px', position: 'relative'}}>
              <ScrollToTop>
                <Switch>
                  <Route exact={true} path='/' render={() => {
                    let url = '';
                    if(_this.state.superAdmin){
                      if (navs[0].children.length) {
                        // console.log("superAdmin")
                        url = navs[0].children[0].path
                      } else {
                        // console.log("superAdmin1")
                        url = navs[0].path
                      }
                    }
                    return <Redirect to={url}/>
                  }}/>
                  {
                    navs.map((record, index) => {
                      // console.log('rec2:',record)
                      if (record.children.length == 0) {
                        console.log('rec2:',record)
                        return <Route key={index} path={record.path} render={(props) => {
                          return _this.authority(record.key, record.component, props)
                        }
                        }/>
                      } else {
                         return record.children.map(item => {
                          return <Route key={item.path} path={item.path} render={(props) => {
                            return _this.authority(item.key, item.component, props)
                          }
                          }/>
                        })
                      }
                    })
                  }
                  <Route path='/myCenter/updatePwd' render={(props) => {
                    return  <Mycenter {...props}/>
                  }}/>
                  {/*<Route render={(props) => <NotFound/>}/>*/}
                </Switch>
              </ScrollToTop>
            </Content>
          </Layout>
        </Layout>
      </HashRouter>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('container'))
